#include <iostream>
#include "opencv2/opencv.hpp"
#include "MVCamera.h"
#include "SingleTrack.h"
#include "UndistortImage.h"
#include "ImageStream.h"
#include "Macros.h"

#include "main_cuda.hpp"
#include "main_default.hpp"

// 图像尺寸
#define FRAME_WIDTH 640
#define FRAME_HEIGHT 368

#define PI 3.14159265

// 帧间隔
#define FRAME_TIME_SPAN 42
// 飞行时间 + 机动时间 + 其他时间
#define TIME_SPAN 0.5
// 直线距离
#define STRAIGHT_DISTANCE 10
// 重力加速度
#define G 9.8
// 装甲板在图像中的像素
#define ARMOUR_WIDTH_PIX 35.86666463157895
#define ARMOUR_HEIGHT_PIX 24.679530213903742
// 装甲板的实际长度
#define ARMOUR_WIDTH_ACT 14.5329608467882
#define ARMOUR_HEIGHT_ACT 10
// 线性尺度倍数 实际长度(m)/像素个数(pix)
#define SCALE 0.4051940986448067
// 绘图框数量
#define CANVAS_COUNT 4

//#define FRAME_WIDTH 600
//#define FRAME_HEIGHT 400

void showResult(const int *trackingFlag, Mat &frame) {
	while (*trackingFlag == 1) {
		if (!frame.empty()) {
			namedWindow("frame");
			imshow("frame", frame);
			startWindowThread();
			waitKey(1);
		}
	}
}

void singleTrackRunning(SingleTrack &st, Rect2d &centerRect, Mat *trackResult, bool displayStream, int *trackingFlag) {
	*trackingFlag = st.startTracking(centerRect, 5, trackResult, displayStream);
}

int main(int argc, char** argv) {
	try {
		cuda::printCudaDeviceInfo(cuda::getDevice());
	} catch (Exception e) {
		cerr << "no CUDA support" << endl;
	}

	VideoCapture video;
	ImageStream ims;

	if (argc > 2) {
		SingleTrack st;
		if (strcmp("video", argv[1]) == 0) {
			cout << "using video file" << endl;
//			初始化视频流
			video = VideoCapture(argv[2]);
			ims.init(&video, FRAME_TIME_SPAN);
		} else if (strcmp("uvc", argv[1]) == 0) {
			cout << "using uvc device" << endl;
			VideoCapture uvc(atoi(argv[2]));
			st = SingleTrack(TrackerType::KCF, uvc, FRAME_WIDTH, FRAME_HEIGHT, CUDA_SUPPORT);
		} else if (strcmp("hikcam", argv[1]) == 0) {
			cout << "using hikcam" << endl;
			mvc::MVCamera mvCamera(atoi(argv[2]));
			mvCamera.openCamera();
			mvCamera.setOutputSize(FRAME_WIDTH, FRAME_HEIGHT);
//			mvCamera.set(mvc::CAP_PROP_EXPOSURE_TIME, (float) 150000);
			mvCamera.startGrabbing();
			st = SingleTrack(TrackerType::KCF, &mvCamera, FRAME_WIDTH, FRAME_HEIGHT, CUDA_SUPPORT);
		} else {
			printf("Unexpected type of input stream.");
			return -1;
		}
//		Rect2d bbox = st.selectTrackingBox(0);
//		st.startTracking(bbox, 0, &trackResult);
	} else {
		printf("Require command.");
		return RETURN_VALUE_ILLEGAL_COMMAND;
	}


#if CUDA_SUPPORT
	return main_cuda(ims);
#else
	return main_default(ims);
#endif

}